﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace JTLeigh.Tools.Development.CopySourceAsHtml
{

	/// <summary>
	/// Reads RTF from the clipboard.
	/// </summary>
    public static class ClipboardRtfReader
    {
        #region Inner Classes and Types

        private class ClipboardRtfReaderState
        {
            public string Rtf { get; set; }
            public bool Successful { get; set; }
        }

        #endregion // Inner Classes and Types

        #region Static Methods

		/// <summary>
		/// Reads RTF from the clipboard.
		/// </summary>
		/// <param name="rtf">The RTF.</param>
		/// <returns><see langword="true"/> if the RTF was read successfully, <see langword="false"/>
		/// otherwise.</returns>
		[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
		public static bool Read(out string rtf)
        {
            ClipboardRtfReaderState state;
            Thread thread;

            state = new ClipboardRtfReaderState();

            thread = new Thread(Read);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start(state);
            thread.Join();

            rtf = state.Rtf;
            return state.Successful;
        }

        private static void Read(object obj)
        {
            ClipboardRtfReaderState state;
            IDataObject dataObject;

            state = (ClipboardRtfReaderState)obj;

            state.Successful = false;
            state.Rtf = null;

            try
            {
                dataObject = Clipboard.GetDataObject();
                state.Successful = true;
                if (dataObject.GetDataPresent(DataFormats.Rtf))
                {
                    state.Rtf = dataObject.GetData(DataFormats.Rtf) as string;
                }
            }
            catch (ExternalException)
            {
            }
		}

        #endregion // Static Methods
    }

}
